import Config from '../config';
import Axios from 'axios';
import iView from 'iview';
import Qs from 'qs';

export const axios = Axios.create({
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    timeout: Config.axiosTimeout,
    transformRequest: [(data) => {
        data = Qs.stringify(data);
        return data;
    }]
});

//登录验证相关……
export const tokenMgr = {
    getToken(formLogin) {
        axios.post(Config.loginUrl, formLogin)
            .then((res) => {
                if (res.data.success == true) {
                    localStorage.username = res.data.username;
                    sessionStorage.token = res.data.token;
                    location.href = '/home';
                } else {
                    iView.Message.error({
                        content: '用户名或密码错误',
                        duration: 3
                    });
                }
            }).catch((err) => {
                console.log(err);
            });
    },
    checkToken() {
        if (!sessionStorage.token) {
            location.href = '/?reLogin=true';
            return;
        }

        axios.post(Config.tokenCheckUrl, {
            token: sessionStorage.token
        }).then((res) => {
            if (res.data == false) {
                location.href = '/';
            }
        });
    },
    reflashToken() {
        axios.post(Config.tokenReflashUrl, {
            username: localStorage.username,
            token: sessionStorage.token
        }).then((res) => {
            sessionStorage.token = res.data;
        });
    },
    deleteToken(){
        sessionStorage.removeItem('token');
        location.href = '/';
    }

};

//在发送请求之前
axios.interceptors.request.use((config) => {
    //附加token信息
    if (sessionStorage.token) {
        config.headers.Authorization = sessionStorage.token;
    }
    return config;
}, (error) => {
    return Promise.reject(error);
});

//返回状态判断
axios.interceptors.response.use((res) => {
    //登录、校验、刷新入口忽略
    if (res.config.url == Config.loginUrl
        || res.config.url == Config.tokenCheckUrl
        || res.config.url == Config.tokenReflashUrl) {
        return res;
    }

    if (res.data.success && res.data.success == false) {
        return Promise.reject(res);
    }

    //刷新token
    tokenMgr.reflashToken();

    return res;
}, (error) => {
    if (error.response.status === 401) {
        if (error.response.data.loginSuccess == false) {
            //token 验证失败
            location.href = '/?reLogin=true';
        }
    } else if (error.response.status === 500) {
        return Promise.reject(error.response.data);
    }

    return Promise.reject(error.response.data);
});


export default {
    install(Vue) {
        Object.defineProperty(Vue.prototype, '$http', { value: axios });
    }
};